﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using E_Learning_V3.Models;
using E_Learning_V3.DAL;
using System.IO;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Web.Helpers;
using System.Collections;

namespace ElearningOUHv2.Controllers
{
    public class AdminSpgController : Controller
    {
        private ElearningContext db = new ElearningContext();

        //
        // GET: /Spg/


        public ViewResult Index()
        {
            //object spgEmne;
            //TempData.TryGetValue("spgEmne", out spgEmne );
            //Session["spgEmne"] = spgEmne;
            string spgEmne = (string)Session["spgEmne"];
            List<Spg> spgList = db.Emner.Where(model => model.emnenavn == spgEmne).First().spgList.ToList();
            return View(spgList);
        }

        //
        // GET: /Spg/Details/5

        public ViewResult Details(int id)
        {
            Spg spg = db.Spg.Find(id);

            return View(spg);
        }

        public ActionResult DisplayImg(int Id)
        {
            Spg spg = db.Spg.Find(Id);
            if (spg != null && spg.billede != null)
            {
                return File(spg.billede, "image/jpg");
            }
            return null;


        }

        //
        // GET: /Spg/Create

        public ActionResult Create()
        {
            return View();
        }



        [HttpPost]
        public ActionResult Create(Spg spg, ICollection<Svarmulighed> svarmuligheder)
        {
            try
            {
                if (ModelState.IsValid)
                {

                    HttpPostedFileBase file = Request.Files[0];
                    byte[] data;
                    using (BinaryReader reader = new BinaryReader(file.InputStream))
                    {
                        data = reader.ReadBytes(file.ContentLength);
                    }
                    spg.billede = data;
                    spg.Svarmuligheder = svarmuligheder;
                    string spgEmne = (string)Session["spgEmne"];
                    db.Emner.Where(model => model.emnenavn == spgEmne).First().spgList.Add(spg);
                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.SaveChanges();

                    return RedirectToAction("Index");
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
            return View(spg);
        }



        //
        // GET: /Spg/Edit/5

        public ActionResult Edit(int id)
        {
            Spg spg = db.Spg.Find(id);
            ViewBag.spg = spg;
            return View(spg);
        }

        //
        // POST: /AdminSpg/Edit/5

        [HttpPost]
        public ActionResult Edit(Spg spg, ICollection<Svarmulighed> svarmuligheder)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Billede
                    HttpPostedFileBase file = Request.Files[0];
                    byte[] data;
                    using (BinaryReader reader = new BinaryReader(file.InputStream))
                    {
                        data = reader.ReadBytes(file.ContentLength);
                    }


                    //Resten
                    Spg trueSpg = db.Spg.Find(spg.spgID);
                    if (data.Length != 0)
                    {
                        trueSpg.billede = data;
                    }
                    trueSpg.spgTekst = spg.spgTekst;
                    trueSpg.situationsTekst = spg.situationsTekst;
                    trueSpg.infoLink = spg.infoLink;
                    int i = 0;
                    foreach (Svarmulighed item in trueSpg.Svarmuligheder)
                    {
                        item.svarTekst = svarmuligheder.ElementAt(i).svarTekst;
                        item.korrekt = svarmuligheder.ElementAt(i).korrekt;
                        i++;
                    }
                    //spg.Svarmuligheder = svarmuligheder;
                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.Entry(trueSpg).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
            return View(spg);
        }



        //
        // GET: /Spg/Delete/5

        public ActionResult Delete(int id)
        {
            Spg spg = db.Spg.Find(id);
            return View(spg);
        }

        //
        // POST: /Spg/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Spg spg = db.Spg.Find(id);
            db.Spg.Remove(spg);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public ActionResult ShowStatistic()
        {
            // finder liste med brugere
            List<StatForUser> svarListe = (from svarItem in db.Svar
                                           select new StatForUser
                                           {
                                               brugerId = svarItem.userId,
                                               antalSpgSvaret = (from svaritem2 in db.Svar
                                                                 where svarItem.userId == svaritem2.userId
                                                                 select svaritem2).Count(),
                                               antalSpgSvaretRigtig = (from svarItem2 in db.Svar
                                                                       from SvarMulighedItem in db.Svarmulighed
                                                                       where svarItem.userId == svarItem2.userId && svarItem2.svarmulighedId == SvarMulighedItem.svarmulighedID && SvarMulighedItem.korrekt == true
                                                                       select svarItem2).Count()
                                           }).Distinct().ToList();

            ViewBag.svarListe = svarListe;

            return View(svarListe);
        }

        public ActionResult GetTestChart()
        {
            // Henter emne fra session
            string spgEmne = (string)Session["spgEmne"];
            if (spgEmne == null)
            {
                spgEmne = db.Emner.First().emnenavn;
            }

            // Laver listen med rigtige svar
            List<StatForSpg> statList = (from spgItem in
                                             (from emneItem in db.Emner
                                              where emneItem.emnenavn == spgEmne
                                              select emneItem).First().spgList
                                         select new StatForSpg
                                         {
                                             spgId = spgItem.spgID,
                                             spgTekst = spgItem.spgTekst,
                                             svarIalt = (from svarItem in db.Svar
                                                         where svarItem.spgId == spgItem.spgID
                                                         select svarItem).Count(),
                                             svarRigtige = (from svarItem in db.Svar
                                                            from svarmulighedItem in db.Svarmulighed
                                                            where svarItem.spgId == spgItem.spgID && svarItem.svarmulighedId == svarmulighedItem.svarmulighedID && svarmulighedItem.korrekt == true
                                                            select svarItem).Count()
                                         }).ToList();


            ArrayList x_ValuesArray = new ArrayList();

            ArrayList y_ValuesArray = new ArrayList();

            for (int i = 0; i < statList.Count; i++)
            {
                x_ValuesArray.Add(statList[i].spgId);
                y_ValuesArray.Add(statList[i].svarRigtige);
            }
            var key = new Chart(width: 600, height: 400, theme: ChartTheme.Blue)

                .AddSeries(

                    chartType: "bar",

                    legend: "Test",

                    xValue: x_ValuesArray,

                    yValues: y_ValuesArray)

                .GetBytes("png");

            return File(key, "image/png");

        }
    }
}